package common;

import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.webapp.WebAppContext;

/**
 * Utility to quickly startup a Jetty server
 * 
 * @author timothystorm
 */
public class Jetty {

	private Server server;

	/**
	 * Creates a Jetty server with default settings. Port = 8080, Context Path =
	 * "/", War Path = "src/main/webapp"
	 */
	public Jetty() {
		this(8080, "/", "src/main/webapp");
	}

	/**
	 * Creates a Jetty server with the provided settins.
	 * 
	 * @param port
	 *            which Jetty will listen for requests, ex. 8080
	 * @param contextPath
	 *            of the applicaiton, ex. "/"
	 * @param warPath
	 *            where the War is located (can be packed or exploded
	 *            directory), ex. "src/main/webapp"
	 */
	public Jetty(int port, String contextPath, String warPath) {
		server = new Server();
		SocketConnector connector = new SocketConnector();
		connector.setPort(port);

		server.setConnectors(new Connector[] { connector });

		WebAppContext context = new WebAppContext();
		context.setServer(server);
		context.setContextPath(contextPath);
		context.setWar(warPath);

		server.setHandler(context);
	}

	public boolean isRunning() {
		return server.isRunning();
	}

	/**
	 * Starts up the Jetty server
	 * 
	 * @throws Exception
	 */
	public void start() throws Exception {
		System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
		server.start();
	}

	/**
	 * Sends the shutdown command. The server will not shut down completely
	 * until all request are complete.
	 * 
	 * @throws Exception
	 */
	public void stop() throws Exception {
		System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
		server.stop();
		server.join();
	}

	/**
	 * This method can be called to startup/shutdown Jetty on demand
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		Jetty jetty = new Jetty();

		try {
			jetty.start();
			
			// wait for user <enter> to shut down the server
			System.in.read();
			jetty.stop();
		}
		catch (Exception e) {
			e.printStackTrace();
			System.exit(100);
		}
	}
}
